<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" plain @click="addroledialog">添加用户</el-button>
      <el-button @click="handDownMoban">下载导入模板</el-button>
      <el-upload
        class="upload-demo"
        action="https://admin.ajhbw.cn/admin/member/importExcel"
        :show-file-list=false
        :on-success="handleFileSuccess"
        list-type="picture"
        :file-list="fileList3" style="display: inline-block">
        <el-button>批量导入文件</el-button>
      </el-upload>
      <el-button @click="handDownload">导出用户</el-button>
    </div>
    <div class="filter-container">
      <el-input clearable @keyup.enter.native="handleFilter" style="width: 150px;" class="filter-item" placeholder="请输入卡号" v-model="listQuery.cardNo">
      </el-input>
      <el-input clearable style="width: 150px;" class="filter-item" placeholder="请输入账号" v-model="listQuery.username" clearable>
      </el-input>
      <el-select clearable v-model="listQuery.provinceId" placeholder="请选择" @change="getcity" style="width: 150px;">
        <el-option
          v-for="item in provinceLIst"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.cityId" placeholder="请选择" @change="getdistrict" style="width: 150px;">
        <el-option
          v-for="item in cityList"
          :key="item.code"
          :label="item.name"
          :value="item.code"
          change="getarea">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.districtId" placeholder="请选择" @change="getstreet" style="width: 150px;">
        <el-option
          v-for="item in districtList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.streetId" placeholder="请选择" style="width: 150px;">
        <el-option
          v-for="item in streetList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.unitId" placeholder="请选择社区">
        <el-option v-for="(item, index) in community" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
      </el-select>
      <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='用户卡号' width="180">
        <template slot-scope="scope">
          {{scope.row.cardNo}}
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center" width="80">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column label="初始密码" align="center" width="80">
        <template slot-scope="scope">
          <span>{{scope.row.initialPass}}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" width="110">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" width="110">
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>
      <el-table-column label="省市区街道" align="center" width="220">
        <template slot-scope="scope">
          <span>{{scope.row.provinceName}},{{scope.row.cityName}},{{scope.row.districtName}},{{scope.row.streetName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属社区" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.unitName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.address}}</span>
        </template>
      </el-table-column>
      <el-table-column label="可用积分" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.integral}}</span>
        </template>
      </el-table-column>
      <el-table-column label="投递总量(g)" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.weight}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.state | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button type="success" size="mini" v-if="scope.row.state == 1" @click="qiyong(scope.row, 'true')" plain>启用</el-button>
          <el-button type="warning" size="mini" v-else @click="jinyong(scope.row, 'false')" plain>禁用</el-button>
          <el-button type="danger" size="mini" @click="shanchu(scope.row, scope.$index)" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]"
                     :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!--分页END-->

    <!--编辑表单弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="formsrules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 470px; margin-left:50px;'>
        <el-form-item label="姓名：" prop="name">
          <el-input type="text" v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input type="tel" v-model="temp.phone"></el-input>
        </el-form-item>
        <el-form-item label="所属社区：" prop="unitId">
          <el-select clearable v-model="temp.unitId" placeholder="请选择社区">
            <el-option v-for="(item, index) in community" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋：" prop="buildingId">
          <el-input type="text" v-model="temp.buildingId"></el-input>
        </el-form-item>
        <el-form-item label="楼层：" prop="floor">
          <el-input type="text" v-model="temp.floor"></el-input>
        </el-form-item>
        <el-form-item label="单元号：" prop="unit">
          <el-input type="text" v-model="temp.unit"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addrole">确 定</el-button>
        <el-button v-else type="primary" @click="sureEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑表单弹窗END-->

    <!--导出条件-->
    <el-dialog title="导出文件" :visible.sync="dialogDownloadVisible">
      <el-form :rules="formsrules" ref="dataForm" :model="downloadCondition" label-position="right" label-width="120px" style='width: 525px; margin-left:50px;'>
        <el-form-item label="卡号：">
          <el-input type="text" v-model="downloadCondition.cardNo"></el-input>
        </el-form-item>
        <el-form-item label="账号：">
          <el-input type="text" v-model="downloadCondition.username"></el-input>
        </el-form-item>
        <el-form-item label="地址选择：">
          <el-select v-model="downloadCondition.provinceId" placeholder="请选择" @change="getcity">
            <el-option
              v-for="item in provinceLIst"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <el-select v-model="downloadCondition.cityId" placeholder="请选择" @change="getdistrict">
            <el-option
              v-for="item in cityList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              change="getarea">
            </el-option>
          </el-select>
          <el-select v-model="downloadCondition.districtId" placeholder="请选择" @change="getstreet">
            <el-option
              v-for="item in districtList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <el-select v-model="downloadCondition.streetId" placeholder="请选择">
            <el-option
              v-for="item in streetList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社区筛选：">
          <el-select clearable v-model="downloadCondition.unitId" placeholder="请选择社区">
            <el-option v-for="(item, index) in community" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDownloadVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureDownload">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑表单弹窗END-->
  </div>
</template>

<script>
  import { getList, updateStart, addroles, sureEdit, shanchu } from '@/api/user/userList'
  import { getcommunity, getareaList } from '@/api/public'

  export default {
    data() {
      const checkPhone = (rule, value, callback) => {
        const mobile = /^(13|18|14|17|15)[0-9]{9}$/
        if (!value) {
          return callback(new Error('请输入手机号码'))
        }
        if (!mobile.test(value)) {
          return callback(new Error('请填写正确的手机号码'))
        } else {
          callback()
        }
      }
      const checkbuild = (rule, value, callback) => {
        const han = /^[\u4e00-\u9fa5]+$/
        if (!value) {
          return callback(new Error('请输入账号'))
        } else if (value.length > 4 | value.length < 1) {
          return callback(new Error('长度在 1 到 4 个字符'))
        } else if (han.test(value)) {
          return callback(new Error('不允许输入汉字'))
        } else {
          callback()
        }
      }
      const checkfloor = (rule, value, callback) => {
        const han = /^[\u4e00-\u9fa5]+$/
        if (!value) {
          return callback(new Error('请输入账号'))
        } else if (value.length > 3 | value.length < 1) {
          return callback(new Error('长度在 1 到 3 个字符'))
        } else if (han.test(value)) {
          return callback(new Error('不允许输入汉字'))
        } else {
          callback()
        }
      }
      const checkunit = (rule, value, callback) => {
        const han = /^[\u4e00-\u9fa5]+$/
        if (!value) {
          return callback(new Error('请输入账号'))
        } else if (value.length > 3 | value.length < 1) {
          return callback(new Error('长度在 1 到 3 个字符'))
        } else if (han.test(value)) {
          return callback(new Error('不允许输入汉字'))
        } else {
          callback()
        }
      }
      return {
        list: null,
        listLoading: true,
        total: null,
        listQuery: {
          id: undefined,
          cardNo: '',
          username: '',
          provinceId: '',
          cityId: '',
          districtId: '',
          streetId: '',
          unitId: ''
        },
        temp: {
          id: undefined,
          name: '',
          phone: '',
          unitId: '',
          buildingId: '',
          floor: '',
          unit: ''
        },
        provinceLIst: [],
        cityList: [],
        districtList: [],
        streetList: [],
        downloadCondition: {
          cardNo: '',
          username: '',
          provinceId: '',
          cityId: '',
          districtId: '',
          streetId: '',
          unitId: ''
        },
        community: [],
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogFormVisible: false,
        dialogDownloadVisible: false,
        formsrules: {
          name: [{ required: true, message: '请输入', trigger: 'blur' }],
          phone: [{ required: true, trigger: 'blur', validator: checkPhone }],
          unitId: [{ required: true, message: '请选择社区', trigger: 'change' }],
          buildingId: [
            { required: true, trigger: 'blur', validator: checkbuild }
          ],
          floor: [
            { required: true, trigger: 'blur', validator: checkfloor }
          ],
          unit: [
            { required: true, trigger: 'blur', validator: checkunit }
          ]
        },
        selected: [],
        fileList3: []
      }
    },
    created() {
      this.fetchData()
      this.getcommunity()
      this.getarea()
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: '已启用',
          1: '已禁用'
        }
        return statusMap[status]
      }
    },
    methods: {
      // 获取列表
      fetchData() {
        this.listLoading = true
        getList(this.listQuery).then(response => {
          this.list = response.data.content
          this.total = response.data.totalElements
          this.listQuery.size = response.data.size
          this.listLoading = false
        })
      },
      getcommunity() {
        getcommunity().then(response => {
          this.community = response.data.content
        })
      },
      getarea() {
        getareaList(undefined).then(res => {
          this.provinceLIst = res.data
        })
      },
      getcity(value) {
        getareaList(value).then(res => {
          this.cityList = res.data
        })
      },
      getdistrict(value) {
        getareaList(value).then(res => {
          this.districtList = res.data
        })
      },
      getstreet(value) {
        getareaList(value).then(res => {
          this.streetList = res.data
        })
      },
      sureDownload() {
        const url = 'https://admin.ajhbw.cn/admin/member/exprot' + '?' + 'cardNo=' + this.downloadCondition.cardNo + '&username=' + this.downloadCondition.username + '&provinceId' + this.downloadCondition.provinceId + '&cityId=' + this.downloadCondition.cityId + '&districtId=' + this.downloadCondition.districtId + '&streetId=' + this.downloadCondition.streetId + '&unitId=' + this.downloadCondition.unitId
        window.open(url)
      },
      handDownMoban() {
        window.open('http://ajwl-file.oss-cn-shenzhen.aliyuncs.com/%E7%94%A8%E6%88%B7%E5%AF%BC%E5%85%A5.xls')
      },
      handleFilter() {
        this.fetchData()
      },
      qiyong(row, status) {
        this.listLoading = true
        const list = {
          uuid: row.uuid,
          state: 0
        }
        updateStart(list).then(response => {
          this.listLoading = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          row.state = 0
        })
      },
      jinyong(row, status) {
        this.listLoading = true
        const list = {
          uuid: row.uuid,
          state: 1
        }
        updateStart(list).then(response => {
          this.listLoading = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          row.state = 1
        })
      },
      addroledialog() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          unitId: '',
          buildingId: '',
          floor: '',
          unit: ''
        }
        this.selected = []
      },
      addrole() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.selected.forEach(item => {
              this.temp.area.push(item)
            })
            addroles(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              location.reload()
            })
          }
        })
      },
      handleFileSuccess(response) {
        if (response.code === 0) {
          this.$notify({
            title: '成功',
            message: response.data,
            type: 'success',
            duration: 2000
          })
        } else {
          this.$message.error(response.msg)
        }
      },
      bianji(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      sureEdit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const temData = Object.assign({}, this.temp)
            sureEdit(temData).then(response => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      shanchu(row) {
        this.$confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          shanchu(row.uuid).then(() => {
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.fetchData()
      },
      handDownload() {
        this.dialogDownloadVisible = true
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .filter-container{
    padding-bottom: 10px;
  }
  .area-select .el-select{
    margin-left: 0;
  }
</style>
